package com.peanut.baby.mvp.launcher;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.igexin.sdk.PushManager;
import com.peanut.baby.AppConfig;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.model.InitialAd;
import com.peanut.baby.model.InitialAdKP;
import com.peanut.baby.mvp.main.MainActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.push.AppPushService;
import com.peanut.baby.push.PushIntentService;
import com.peanut.baby.util.Cache;
import com.peanut.baby.util.PrefUtil;
import com.peanut.devlibrary.BaseActivity;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.tencent.mars.xlog.Log;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/6/14.
 */

public class StartupActivity extends BaseActivity implements LauncherContract.View, View.OnClickListener{
    static final String TAG = StartupActivity.class.getSimpleName();
    private static final long LAUNCHER_DELAY_TIME = 5000;
    @BindView(R.id.launcher_skip)
    TextView skip;
    @BindView(R.id.spalsh_image)
    ImageView splashImage;
    private long startTime;

    private LauncherContract.Presenter presenter;
//    private Handler handler = new Handler();
    private Runnable    switchRunnable;

    private AlertDialog alertDialog;

    private Timer countDownTimer;
    private TimerTask countDownTimerTask;

    int count = 5;

    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            int count = msg.arg1;
            if(count == 0){
                skip.setVisibility(View.GONE);
                switchOut();
            }else {
                skip.setText("跳过("+count+")");

            }
        };
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        ButterKnife.bind(this);
        skip.setOnClickListener(this);
        startTime = System.currentTimeMillis();
        presenter = new LauncherPresenter(this,this);
        presenter.checkPermission(this);
    }


    @Override
    public void switchLogin() {

    }

    @Override
    public void switchMain() {

    }

    @Override
    public void onGetAdError(String msg) {
        Log.d("TAG","onGetAdError "+(alertDialog == null || !alertDialog.isShowing()));
        if(alertDialog == null || !alertDialog.isShowing()){
            //当前没弹窗
            switchDelayed();
        }

    }

    @Override
    public void onGetAdSuccess(InitialAd ad) {
        if(ad == null || ad.kp == null){
            switchDelayed();
            return;
        }
        if(ad.tk != null){
            Cache.tkAd = ad.tk;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(ad.kp != null){
                    if(ad.kp.imgUrl.endsWith("gif")){
                        ImageLoader.getInstance().loadImageViewGif2(StartupActivity.this, ad.kp.imgUrl, splashImage, R.drawable.splash, R.drawable.splash, new RequestListener() {
                            @Override
                            public boolean onException(Exception e, Object model, Target target, boolean isFirstResource) {
                                if(alertDialog == null|| !alertDialog.isShowing()){
                                    startCountDownTimer();
                                }

                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Object resource, Object model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {


                                skip.setVisibility(View.VISIBLE);
                                splashImage.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        removeCallbackAndTimerSwitchToAd(ad.kp);
                                    }
                                });
                                //有弹窗的时候不倒计时
                                if(alertDialog == null|| !alertDialog.isShowing()){
                                    startCountDownTimer();
                                }
                                return false;
                            }
                        });
                    }else{
                        ImageLoader.getInstance().loadImageViewLoding(StartupActivity.this, ad.kp.imgUrl, splashImage, R.drawable.splash, R.drawable.splash);
                        skip.setVisibility(View.VISIBLE);
                        splashImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                removeCallbackAndTimerSwitchToAd(ad.kp);
                            }
                        });
                        //有弹窗的时候不倒计时
                        if(alertDialog != null && alertDialog.isShowing()){
                            return;
                        }
                        startCountDownTimer();
                    }

                }
            }
        });

    }


    private void startCountDownTimer(){
        countDownTimer = new Timer();
        countDownTimerTask = new TimerTask() {
            @Override
            public void run() {
                if(alertDialog != null && alertDialog.isShowing()){
                    //当前有弹窗 倒计时暂停
                    return;
                }
                Message message = new Message();
                message.arg1 = count;
                if(count!=-1){
                    count--;
                }else {
                    return;
                }
                handler.sendMessage(message);
            }
        };
        countDownTimer.schedule(countDownTimerTask,0,1000);
    }


    private void removeCallbackAndTimerSwitchToAd(InitialAdKP kpAd){
        handler.removeCallbacks(switchRunnable);
        cancelTimer();
        MainActivity.start(StartupActivity.this);
        WebViewActivity.start(StartupActivity.this,kpAd.htmlUrl,kpAd.name,"");

        finish();
    }

    @Override
    public void onPermissionGranted(List<String> grantPermissions) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PushManager.getInstance().initialize(StartupActivity.this, AppPushService.class);
                PushManager.getInstance().registerPushIntentService(StartupActivity.this, PushIntentService.class);
            }
        });
        checkTipsDialog();

    }

    private void checkTipsDialog(){
        boolean displayed = PrefUtil.getBoolean(AppConfig.PrefConfig.PREF_PRIVACY_DIALOG);
        presenter.getAd();
        if(!displayed){
            alertDialog = new BaseDialog().showWenxiTishi(StartupActivity.this, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PrefUtil.saveBoolean(AppConfig.PrefConfig.PREF_PRIVACY_DIALOG, true);
                    //判断广告是不是有
                    if(skip.getVisibility() == View.VISIBLE){
                        startCountDownTimer();
                    }else{
                        switchOut();
                    }
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    checkPrivacyDialog();
                }
            });
        }else{

        }
    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {
        checkTipsDialog();
    }

    private void checkPrivacyDialog(){
        boolean displayed = PrefUtil.getBoolean(AppConfig.PrefConfig.PREF_PRIVACY_DIALOG);

        if(!displayed){
            alertDialog = new BaseDialog().showPrivacyDialog(StartupActivity.this,  new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PrefUtil.saveBoolean(AppConfig.PrefConfig.PREF_PRIVACY_DIALOG, true);
                    if(skip.getVisibility() == View.VISIBLE){
                        startCountDownTimer();
                    }else{
                        removeCallbackAndTimeAndWitchToMain();
                    }

                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    public void switchDelayed() {
        switchRunnable = new Runnable() {
            @Override
            public void run() {
                switchOut();
            }
        };
        handler.postDelayed(switchRunnable, getSwitchTimeLeft());
    }


    /**
     * delaytime  - (current time  - startTime)
     *
     * @return
     */
    public long getSwitchTimeLeft() {
        long timePassed = System.currentTimeMillis() - startTime;
        if (timePassed > LAUNCHER_DELAY_TIME) {
            return 0;
        } else {
            return LAUNCHER_DELAY_TIME - timePassed;
        }
    }

    private void switchOut(){
        if(isFinishing()){return;}
        cancelTimer();


        MainActivity.start(StartupActivity.this);
        finish();
    }

    private void cancelTimer(){
        try {
            if(countDownTimerTask != null){
                countDownTimerTask.cancel();
            }
            if(countDownTimer != null){
                countDownTimer.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.launcher_skip:
                removeCallbackAndTimeAndWitchToMain();
                break;
        }
    }

    private void removeCallbackAndTimeAndWitchToMain(){
        Log.d("LauncherActivity","launcher_skip");
        handler.removeCallbacks(switchRunnable);
        cancelTimer();
       MainActivity.start(StartupActivity.this);
       finish();
    }


}
